package org.flashamaphone.voices.waveformFactories
{
	import org.flashamaphone.voices.waveformFactories.WaveFactory;
	
	public class HarmonicOvertoneWaveform extends WaveFactory
	{
		/** number of harmonic overtones */
		public var harmonicOvertones:int;
		
		/** harmonic phase randomizations */
		protected var _phaseRandomizations:Array = new Array();
		
		/** wave factory */
		protected var _wavefactory:IWaveFactory;
		
		/**
		 * harmonic overtone waveform
		 * 
		 * @param number of harmonic overtones
		 * @param wave factory
		 */
		public function HarmonicOvertoneWaveform( harmonicOvertones:int = 1, wavefactory:IWaveFactory = null, phaseRandomizations:Array = null )
		{
			this.harmonicOvertones = harmonicOvertones;
			
			if (phaseRandomizations) {
				_phaseRandomizations = phaseRandomizations;
			}
			
			if (!wavefactory) {
				_wavefactory = new SineWaveFactory();
			} else {
				_wavefactory = wavefactory;
			}
			super();
		}
		
		/**
		 * sample a sin wave at a phase
		 */
		public override function sample(phase:Number):Number {
			phase = phaseCorrection(phase);
			var sample:Number = 0;
			for (var c:int = 0; c < harmonicOvertones; c++ ) {
				var rndm:Number = 1;
				if(_phaseRandomizations.length > c) {
					rndm = _phaseRandomizations[c];
				}
				sample += _wavefactory.sample(phase * rndm);
				phase *= 2; // get next harmonic - one octave up
			}
			return sample/harmonicOvertones;
		}
	}
}